<template>
    <el-form :model="formData" :rules="rules" ref="formRef" :label-width="labelWidth" :inline="inline"
        :label-position="labelPosition">
        <el-form-item v-for="(item, index) in formItems" :key="index" :label="item.label" :prop="item.prop"
            :rules="item.rules">
            <component v-if="!item.slot" :is="item.component" v-model="formData[item.prop]" v-bind="item.attrs"
                v-on="item.listeners || {}">
                <template v-if="item.component === 'el-select' && item.options">
                    <el-option v-for="opt in item.options" :key="opt.value" :label="opt.label" :value="opt.value" />
                </template>
            </component>
            <slot v-else :name="item.slot" :formData="formData" :item="item"></slot>
        </el-form-item>
        <el-form-item v-if="!isHiddenButton">
            <slot name="actions">
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm">取消</el-button>
            </slot>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { ref } from 'vue';

const props = defineProps({
    formItems: {
        type: Array,
        required: true,
    },
    formData: {
        type: Object,
        required: true,
    },
    rules: {
        type: Object,
        default: () => ({}),
    },
    inline: {
        type: Boolean,
        default: false,
    },
    labelWidth: {
        type: String,
        default: 'auto',
    },
    labelPosition: {
        type: String,
        default: 'right',
    },
    isHiddenButton: {
        type: Boolean,
        default: false
    }
});

const emit = defineEmits(['submit']);
const formRef = ref(null);

const submitForm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                emit('submit', props.formData);
            } catch (error) {
                console.error('表单提交失败:', error);
            }
        } else {
            console.log('表单验证失败');
        }
    });
};
const resetForm = () => {
    formRef.value.resetFields();
};
</script>